package com.skivingcloud.admin.sys.service.impl;

import com.skivingcloud.admin.sys.entity.SysUserMenu;
import com.skivingcloud.admin.sys.entity.SysUserStation;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.sys.entity.UserRes;
import com.skivingcloud.admin.sys.mapper.SysUserMenuMapper;
import com.skivingcloud.admin.sys.mapper.SysUserStationMapper;
import com.skivingcloud.admin.sys.mapper.UserMapper;
import com.skivingcloud.admin.sys.service.IUserService;
import com.skivingcloud.admin.utils.PasswordHelper;
import com.skivingcloud.common.contants.Constant;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONObject;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author skivingcloud
 * @since 2022-01-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

	@Autowired
	private SysUserStationMapper sysUserStationMapper;
	@Autowired
	private SysUserMenuMapper sysUserMenuMapper;
	
	@Override
	public List<Map<String, Object>> getResourcesByUserId(String id) {
		List<Map<String, Object>> list = this.baseMapper.getResourcesByUserId(id);
		return list;
	}

	@Override
	public List<User> getUser(User user) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		if(StringUtils.isNotBlank(user.getId())) {
			queryWrapper.eq("id", user.getUsername());
		}
		if(StringUtils.isNotBlank(user.getUsername())) {
			queryWrapper.eq("username", user.getUsername());
		}
		if(StringUtils.isNotBlank(user.getAccountName())) {
			queryWrapper.eq("account_name", user.getAccountName());
		}
		if(StringUtils.isNotBlank(user.getStatus())) {
			queryWrapper.eq("status", user.getStatus());
		}
		if(StringUtils.isNotBlank(user.getOrgId())) {
			queryWrapper.eq("org_id", user.getOrgId());
		}
		if(StringUtils.isNotBlank(user.getTenantId())) {
			queryWrapper.eq("tenant_id", user.getTenantId());
		}
		if(StringUtils.isNotBlank(user.getIdType())) {
			queryWrapper.eq("id_type", user.getIdType());
		}
		if(StringUtils.isNotBlank(user.getIdNo())) {
			queryWrapper.eq("id_no", user.getIdNo());
		}
		return this.baseMapper.selectList(queryWrapper);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void update(User userUpdate) {
		this.baseMapper.updateById(userUpdate);
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params, User user) {
		PageUtils pageUtils = PageUtils.getPageInfo(params);
		Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		JSONObject dataForm = JSONObject.fromObject(params.get("dataForm"));
		Map<String, Object> paramsNew = new HashMap<String, Object>();
		if (dataForm.get("username") != null && !"".equals(dataForm.get("username"))) {
			paramsNew.put("username", "%" + dataForm.get("username").toString() + "%");
		}
		if(dataForm.get("staffName")!=null&&!"".equals(dataForm.get("staffName"))){
			paramsNew.put("staffName", "%" + dataForm.get("staffName").toString() + "%");
		}
		if(dataForm.get("staffId")!=null&&!"".equals(dataForm.get("staffId"))){
			paramsNew.put("staffId", "%" + dataForm.get("staffId").toString() + "%");
		}
		if(dataForm.get("tenantName")!=null&&!"".equals(dataForm.get("tenantName"))){
			paramsNew.put("tenantName", "%" + dataForm.get("tenantName").toString() + "%");
		}
		if(!user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			paramsNew.put("tenantId", user.getTenantId());
		}
		paramsNew.put("statusDel", Constant.USER_STATUS_DELETED);
		this.baseMapper.selectByParams(paramsNew);
		pageUtils = new PageUtils(p);
		return pageUtils;
	}

	@Override
	public boolean checkUserName(String username, String tenantId) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq("username", username).eq("tenant_id", tenantId);
		List<User> list = this.baseMapper.selectList(queryWrapper);
		if (!list.isEmpty()) {
			return true;
		}
		return false;
	}

	/**
	 * 获取用户岗位信息
	 * 
	 * @param userId
	 * @return
	 */
	@Override
	public List<SysUserStation> getUserStationList(String userId) {
		QueryWrapper<SysUserStation> queryWrapper = new QueryWrapper<SysUserStation>();
		queryWrapper.eq("user_id", userId);
		return sysUserStationMapper.selectList(queryWrapper);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void setUserStation(String userId, List<SysUserStation> stationList, User userOp) {
		// 先删掉原来的岗位关联
		QueryWrapper<SysUserStation> queryWrapper = new QueryWrapper<SysUserStation>();
		queryWrapper.eq("user_id", userId);
		sysUserStationMapper.delete(queryWrapper);
		for (SysUserStation userStation : stationList) {
			sysUserStationMapper.insert(userStation);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public String resetPassword(String userId, User opUser) {
		User user = this.baseMapper.selectById(userId);
		// 生成随机密码
		String passNew = PasswordHelper.generatePassword(10);
		User userNew = new User();
		BeanUtils.copyProperties(user, userNew);
		userNew.setPassword(passNew);
		userNew = PasswordHelper.encryptPassword(userNew);
		LocalDateTime lastChnagedTime = LocalDateTime.now();
		userNew.setLastChangeder(opUser.getId());
		userNew.setLastChnagedTime(lastChnagedTime);
		userNew.setLastChangedPwdTime(lastChnagedTime);
		this.baseMapper.updateById(userNew);
		return passNew;
	}

	/**
	 * 批量删除
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String[] userIds) {
		this.baseMapper.deleteBatchIds(Arrays.asList(userIds));
	}

	/**
	 * 查询用户资源关系
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public List<SysUserMenu> getResTreeByUserId(String id) {
		QueryWrapper<SysUserMenu> queryWrapper = new QueryWrapper<SysUserMenu>();
		queryWrapper.eq("user_id", id);
		return sysUserMenuMapper.selectList(queryWrapper);
	}

	/**
	 * 设置用户资源权限
	 * 
	 * @param userRes
	 * @param userSession
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void setSysUserMenu(UserRes userRes, User userSession) {
		// 先删除角色资源关联再增加
		if (userSession.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			QueryWrapper<SysUserMenu> queryWrapper = new QueryWrapper<SysUserMenu>();
			queryWrapper.eq("user_id", userRes.getId());
			sysUserMenuMapper.delete(queryWrapper);
		} else {
			QueryWrapper<SysUserMenu> queryWrapper = new QueryWrapper<SysUserMenu>();
			queryWrapper.eq("user_id", userRes.getId());
			sysUserMenuMapper.delete(queryWrapper);
		}
		for (String resid : userRes.getResId()) {
			SysUserMenu rm = new SysUserMenu();
			rm.setId(UuidUtil.get32UUID());
			rm.setMenuId(resid);
			rm.setUserId(userRes.getId());
			sysUserMenuMapper.insert(rm);
		}
	}

	/**
	 * 比较通用的用户查询，只查当前租户的，查询条件为部门名称和姓名
	 * 
	 * @param params
	 * @param user
	 * @return
	 */
	@Override
	public PageUtils queryUserSkiving(Map<String, Object> params, User user) {
		PageUtils pageUtils = PageUtils.getPageInfo(params);
		Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		String orgName = params.get("orgName") == null ? null : params.get("orgName").toString();
		String staffName = params.get("staffName") == null ? null : params.get("staffName").toString();
		Map<String, String> pMap = new HashMap<>();
		if(StringUtils.isNotBlank(orgName)){
			pMap.put("orgName", "%" + orgName + "%");
		}
		if (StringUtils.isNotBlank(staffName)) {
			pMap.put("staffName", "%" + staffName + "%");
		}
		pMap.put("tenantId", user.getTenantId());
		this.baseMapper.queryUserSkiving(pMap);
		pageUtils = new PageUtils(p);
		return pageUtils;
	}
	
	/**
	 * 查找所有的用户
	 * 
	 * @param tenantId
	 * @return
	 */
	@Override
	public List<User> getAllUserByTenantId(String tenantId) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		queryWrapper.eq("status", Constant.USER_STATUS_NORMAL).eq("tenant_id", tenantId);
		List<User> list = this.baseMapper.selectList(queryWrapper);
		return list;
	}
}
